package oop.controller.api.section;

import java.sql.SQLException;

import oop.controller.api.APIAction;
import oop.controller.api.APIFailedResult;
import oop.data.Section;
import oop.db.dao.SectionDAO;
import oop.db.dao.TestVersionDAO;

public class Create extends APIAction {

	@Override
	protected Object performImpl() throws Exception {
		long testId = params().getLong("testId");
		try {
			TestVersionDAO.dropByTest(testId);
		} catch (SQLException e) {
			if (e.getErrorCode() == 1451) {
				return new APIFailedResult("using", "Không thể sửa đề thi đang sử dụng");
			} else {
				throw e;
			}
		}
		
		String text = params().getString("text");
		int order = SectionDAO.nextAvailableOrder(testId);
		Section section = SectionDAO.create(text, order, testId);

		return success().addProperty("newId", section.getId()).addProperty(
				"newText", section.getText());
	}

}
